<?php

namespace App\Http\Controllers\Company;

use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyVisitRecord;
use App\Models\Personal\BrowseCompany;
use App\Models\Personal\Resume;
use App\Models\Personal\ResumeSend;
use Illuminate\Http\Request;
use App\Models\Personal\PersonalUser;
use App\Models\Company\CompanyUser;
use App\Http\Requests\Company\Login\AjaxCompanyLoginRequest;
use App\Models\Company\CompanyJob;
use League\Flysystem\Exception;
use Style, Site, Auth, Session, log;

require_once(app_path('Vendor/MpWeiXin/MpWeiXin.php'));

class MpWeiXinController extends CommonController{
    private $access_token = '';//access_token 默认值为空

    /**
     * 微信链接页面
     * @param Request $request
     */
    public function WeiXinLink(Request $request){
        $echoStr = $request->input('echostr');
        if( isset($echoStr) ){
            $wechatObj = new \MpWeiXin();
            $wechatObj->valid('company');//$request
            exit;
        }

        $postStr = file_get_contents('php://input');

        if( !empty($postStr) ){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch( $RX_TYPE ){
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            return response($resultStr)->header('Content-Type', "text/xml");
        }else{
            echo "";
            exit;
        }

    }

    /**
     * 个人用户搜索 图文回复
     * @param $postObj
     * @return string
     */
    public function handleText($postObj){
        $toUsername = $postObj->ToUserName;
        $fromUsername = $postObj->FromUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $firstPigUrl = asset("default/images/mobile/layout/weichatsearchbg.png");//第一副大图 背景图

        $pigurl = asset("default/images/mobile/layout/jiantou.png"); //列表 右边背景图
        $Resume = Resume::select('id', 'name', 'intentionjobs')->where('intentionjobs', 'like', '%' . $keyword . '%')->where('resume_status', 1)->take(6)->get();

        if( count($Resume) > 0 ){
            $title = "共搜索到{" . count($Resume) . "}" . $keyword . "关联人才";
            $firstLink = url("mobile/personnel?keyword=$keyword");  //第一副大图 链接
            $countnews = count($Resume) + 1;
            $msgType = "news";
            $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount>$countnews</ArticleCount>
                <Articles>

                <item>
                <Title><![CDATA[" . $title . "]]></Title>
                <Description><![CDATA[描述]]></Description>
                <PicUrl><![CDATA[$firstPigUrl]]></PicUrl>
                <Url><![CDATA[$firstLink]]></Url>
                </item>
            ";
            foreach($Resume as $v){
                $url = url("resume_" . idEncryption($v->id) . ".html");
                $textTpl .= "<item>
                    <Title><![CDATA[" . $v->name . "]]></Title>
                    <Description><![CDATA[" . $v->name . "]]></Description>
                    <PicUrl><![CDATA[$pigurl]]></PicUrl>
                    <Url><![CDATA[$url]]></Url>
                    </item>";
            }

            $textTpl .= "</Articles></xml>";

            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);
        }else{
            $msgType = "text";
            $contentStr = "抱歉，未找到相关信息";
            $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>
					";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        }

        return $resultStr;
    }

    /**
     * 消息 中心
     * @param $object
     */
    public function messageCenter($postObj, $extLink){
        $toUsername = $postObj->ToUserName;
        $fromUsername = $postObj->FromUserName;

        $time = time();
        $firstPigUrl = asset("default/images/mobile/layout/havenewmessage.png");//第一副大图 背景图
        $firstLink = url("mobile/company/welcome") . "/?wechatmpopenid=$fromUsername&$extLink";  //第一副大图 链接
        $pigurl = asset("default/images/mobile/layout/jiantou.png"); //列表 右边背景图

        $msgType = "news";
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>4</ArticleCount>
            <Articles>

            <item>
            <Title><![CDATA[消息中心]]></Title>
            <Description><![CDATA[描述]]></Description>
            <PicUrl><![CDATA[$firstPigUrl]]></PicUrl>
            <Url><![CDATA[$firstLink]]></Url>
            </item>
        ";
        //收到的应聘简历
        $Link = url("mobile/company/resume_message") . "/?wechatmpopenid=$fromUsername&$extLink";
        //获得用户uid
        $user = CompanyUser::select('uid')->where('wechatmpopenid', $fromUsername)->first();
        $resumeCount = ResumeSend::where('company_uid', $user->uid)->where('status', 0)->count();
        $textTpl .= "<item>
                <Title><![CDATA[($resumeCount)份未读简历]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[$pigurl]]></PicUrl>
                <Url><![CDATA[$Link]]></Url>
                </item>";

        //发布的岗位、
        $CompanyCount = CompanyJob::where('uid', $user->uid)->where('job_status', 1)->count();
        $Link = url("mobile/company/jobadmin") . "/?wechatmpopenid=$fromUsername&$extLink";
        $textTpl .= "<item>
                <Title><![CDATA[发布的岗位($CompanyCount)]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[$pigurl]]></PicUrl>
                <Url><![CDATA[$Link]]></Url>
                </item>";

        //多少人浏览过我
        $BrowseCount = BrowseCompany::where('company_uid', $user->uid)->count();
        $BrowseCount = intval($BrowseCount);
        $Link = url("mobile/company/browse_company") . "/?wechatmpopenid=$fromUsername&$extLink";
        $textTpl .= "<item>
                <Title><![CDATA[($BrowseCount)浏览过我]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[$pigurl]]></PicUrl>
                <Url><![CDATA[$Link]]></Url>
                </item>";

        $textTpl .= "</Articles></xml>";

        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);

        return $resultStr;
    }

    /**
     * 关注
     * @param $object
     * @return string
     */
    public function handleEvent($object){
        $contentStr = "";
        switch( $object->Event ){
            case "subscribe":
                //新用户关注事件
                $openid = $object->FromUserName;
                $output = $this->getMpUserInfo($openid);

                try{
                    if( !empty($output->errcode) ){
                        throw new Exception("感谢您的关注");
                    }

                    //查找用户是否已使用微信登录
                    if( !empty($output->unionid) ){
                        if( $CompanyUser = CompanyUser::select('uid', 'wechatunionid')->where('wechatunionid', $output->unionid)->first() ){
                            //使用微信登录过，有unionid,直接绑定用户
                            $CompanyUser->wechatmpopenid = $output->openid;
                            $CompanyUser->save();
                        }
                    }

                    $contentStr = "感谢您的关注,等您好久了!";
                }catch( Exception $e ){
                    $contentStr = 'Message: ' . $e->getMessage();
                }
                $resultStr = $this->responseText($object, $contentStr);
                break;
            case "CLICK":
                $contentStr = $object->EventKey;
                if( !empty($object->EventKey) ){
                    switch( $object->EventKey ){
                        case "reFresh"://刷新

                            if( $user = CompanyUser::select('uid')->where('wechatmpopenid', $object->FromUserName)->first() ){

                                if( CompanyJob::where('uid', $user->uid)->update(['updatetime' => date("Y-m-d H:i:s", time())]) ){
                                    $contentStr = "岗位刷新成功";
                                }else{
                                    $contentStr = "岗位刷新失败,<a href='" . url("mobile/company/jobadmin") . "'>创建一份工作岗位</a>";
                                }

                            }else{

                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);
                                //查找用户是否有unionid
                                if( !empty($output->unionid) ){
                                    $link = "unionid=" . $output->unionid . "&openid=$openid";
                                }else{
                                    $link = "unionid=openid=$openid";
                                }
                                $contentStr = "/::) " . "亲，请先绑定账号，<a href='" . url("mobile/company/binding") . "?$link'>绑定账号/注册新账号</a>";

                            }

                            $resultStr = $this->responseText($object, $contentStr);
                            break;
                        case "userMessage"://消息中心

                            if( $user = CompanyUser::select('uid','password')->where('wechatmpopenid', $object->FromUserName)->first() ){
                                $strPassword = substr($user->password, 0 ,16);//取密码前16
                                $strEncryption = md5($strPassword . date('Y-W'));//拼接当前周数md5加密
                                $redirectType = 1;//验证没通过是否重定向，1是0否
                                $extLink = "str=$strEncryption&redirect=$redirectType";
                                return $this->messageCenter($object, $extLink);
                            }else{
                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);
                                //查找用户是否有unionid
                                if( !empty($output->unionid) ){
                                    $link = "unionid=" . $output->unionid . "&openid=$openid";
                                }else{
                                    $link = "openid=$openid";
                                }
                                $contentStr = "/::) " . "亲，请先绑定账号，<a href='" . url("mobile/company/binding") . "?$link'>绑定账号/注册新账号</a>";
                                $resultStr = $this->responseText($object, $contentStr);
                            }

                            break;
                        case "binDing"://账号绑定

                            //查找用户是否已绑定
                            if( $CompanyUser = CompanyUser::select('uid', 'username')->where('wechatmpopenid', $object->FromUserName)->first() ){
                                $contentStr = "/::) 亲爱的" . $CompanyUser->username . '，您的账号已绑定完成，如需解绑请点下面链接';
                                $contentStr .= "<a href='" . url("company/clearbinding/" . $CompanyUser->uid . "/" . $object->FromUserName) . "'>{解绑账号}</a>";

                            }else{
                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);

                                try{
                                    //如果有异常
                                    if( !empty($output->errcode) ){
                                        throw new Exception("绑定失败");
                                    }
                                    //查找用户是否有unionid
                                    if( !empty($output->unionid) ){
                                        $link = "unionid=" . $output->unionid . "&openid=$openid";
                                    }else{
                                        $link = "openid=$openid";
                                    }
                                    $contentStr = "/::) " . "<a href='" . url("mobile/company/binding") . "?$link'>点击->绑定账号/注册新账号</a>";

                                }catch( Exception $e ){

                                    $contentStr = 'Message: ' . $e->getMessage();
                                    break;

                                }
                            }
                            $resultStr = $this->responseText($object, $contentStr);
                            break;
                        default :

                            break;
                    }
                }

                break;
            default :
                $contentStr = "Unknow Event: " . $object->Event;
                //$resultStr = $this->responseText($object, $contentStr);//未知事件提示
                $resultStr='';
                break;
        }

        return $resultStr;
    }

    /**
     * 通过openid 拉取公众平台用户信息
     * @param $openid
     * @return mixed
     */
    public function getMpUserInfo($openid){
        //拉取用户信息
        $wechatObj = new \MpWeiXin();
        $ACCESS_TOKEN = $this->tokenValue(1);
        $openid = $openid;  //关注用户onpen id
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$ACCESS_TOKEN&openid=$openid&lang=zh_CN";
        $output = $wechatObj->curlSetopt($url);
        return $output;
    }


    /**
     * 微信解除账号绑定
     * @param $uid
     * @return mixed
     */
    public function clearBinDing($uid, $wechatmpopenid){
        if( !empty($uid) ){
            CompanyUser::where('uid', $uid)->update(['wechatopenid' => NULL, 'wechatmpopenid' => NULL, 'wechatunionid' => NULL]);
            $data = [
                'touser' => $wechatmpopenid,
                'msgtype' => 'text',
                'text' => ['content' => '解绑成功']
            ];
        }else{
            $data = [
                'touser' => $wechatmpopenid,
                'msgtype' => 'text',
                'text' => ['content' => '解绑失败']
            ];
        }

        $access_token = $this->tokenValue(1);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";

        $data = json_encode($data, JSON_UNESCAPED_UNICODE);//中文不转unicode
        $wechatObj = new \MpWeiXin();
        $wechatObj->pushDate($data, $url);
        $status = "clear";
        return Style::view("mobile/company/auth/binDingStatus", compact('status'));
    }

    /**
     * 文本消息
     * @param $object
     * @param $content
     * @param int $flag
     * @return string
     */
    public function responseText($object, $content, $flag = 0){
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    /**
     * 获取token,检查时间，提前十分钟更新token
     * @param $catetory
     * @return mixed
     */
    private function tokenValue($catetory){

        $wechatObj = new \MpWeiXin();
        return $wechatObj->checkToken('company', $catetory);

    }

    /**
     * 微信登录
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function weiXinOpenLogin(Request $request){
        $request->only('code', 'state');
        $appid = Site::get('mpCompanyOpenAppID');
        $secret = Site::get('mpCompanyOpenAppSecret');
        $code = $request->code;
        $state = $request->state;
        //获得token
        if( $state == Site::get('mpCompanyOpenState') && !empty($code) ){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//以文件流的方式返回
            $output = curl_exec($curl);
            curl_close($curl);
            $get_at_array = json_decode($output);

            if( is_object($get_at_array) ){
                if( empty($get_at_array->access_token) || empty($get_at_array->openid) ){
                    return redirect("/company/login")->with('errMsg', '抱歉，微信登录失败，请重新扫一次！！');
                }
                $access_token = $get_at_array->access_token;
                $openid = $get_at_array->openid;
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//以文件流的方式返回
                $output = curl_exec($curl);
                curl_close($curl);
                $getUserInfo = json_decode($output);
                //获得用户信息
                if( empty($getUserInfo->unionid) || empty($getUserInfo->openid) ){
                    return redirect("/company/login")->with('errMsg', '抱歉，微信登录失败，请重新扫一次！！');
                }else{
                    $usname = $getUserInfo->nickname;//用户名
                    $userImg = $getUserInfo->headimgurl;//头像

                    $openId = $getUserInfo->openid;
                    $unionid = $getUserInfo->unionid;
                    $CompanyUser = CompanyUser::where('wechatopenid', $openId)->orWhere('wechatunionid', $unionid)->first();

                    $user = auth()->guard('company')->user();
                    if( $CompanyUser ){//已注册过
                        Auth::guard('company')->login($CompanyUser);

                        $user = auth()->guard('company')->user();
                        //登录记录表
                        $this->loginRecord($user);
                        //更新用户表
                        $this->updateUser($user);

                        return redirect("/");
                    }elseif( !empty($user->uid) ){//已登陆账号直接邦定
                        $user->wechatopenid = $openId;
                        $user->wechatunionid = $unionid;
                        $user->save();
                        return redirect("company/set_account");
                    }else{
                        //查询companyLogin 是否等1，等于1直接登录
                        switch( Site::get('mpCompanyOpenlogin') ){
                            case 0:
                                Session::put('openId', $openId);
                                Session::put('unionid', $unionid);
                                Session::put('userImg', $userImg);
                                Session::put('usname', $usname);
                                return redirect('company/weixinbinding');
                                break;
                            case 1:
                                if( !empty($openId) ){
                                    $rename = $this->rename($usname);
                                    $create = [
                                        'username' => $rename,
                                        'email' => '',
                                        'password' => str_random(60),
                                        'wechatopenid' => $openId,
                                        'wechatunionid' => $unionid?$unionid:null,
                                        'regtime' => date('Y-m-d H:i:s', time()),
                                        'updatetime' => date('Y-m-d H:i:s', time()),
                                        'last_login_time' => date('Y-m-d H:i:s', time()),
                                        'last_login_ip' => getIp()
                                    ];

                                    if( $newUser = CompanyUser::create($create) ){
                                        Auth::guard('company')->login($newUser);
                                        $user = auth()->guard('company')->user();
                                        //登录记录表
                                        $this->loginRecord($user);
                                        return redirect("/");
                                    }else{
                                        return redirect('company/weixinbinding');
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }
        return redirect("/company/login")->with('errMsg', '抱歉，微信登录失败，请重新扫一次！！');
    }


    /**
     * 个人微信绑定现在账号
     * @param Request $request
     * @return mixed
     */
    public function WeiXinBinDing(){
        $userImg = session('userImg');
        $usname = session('usname');
        //Session::forget('usname');
        $toRegNewUserDir = "company/newweixinbinding";
        $formDir = "company/stroyweixinbinding";
        if( Session::has('openId') ){
            return Style::view("company.auth.binDingRegister", compact('userImg', 'usname', 'toRegNewUserDir', 'formDir'));
        }else{
            return redirect('/company/login');
        }
    }

    /**
     * 个人微信绑定新注册用户
     */
    public function newWeiXinBinDing(){
        if( Session::has('openId') ){
            $openId = session('openId');
            $unionid = session('unionid');
            $openIdType = 'mp';
            return Style::view("company.auth.newBinDingRegister", compact('openId', 'unionid', 'openIdType'));//
        }else{
            return redirect('/company/login');
        }
    }

    /**
     * 保存企业微信绑定openId
     * @param AjaxCompanyLoginRequest $request
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function stroyWeiXinBinDing(AjaxCompanyLoginRequest $request){
        $request->only('username', 'password');
        $request->flash();
        if( !Session::has('openId') ){
            return redirect('/company/login')->with('errMsg', '绑定失败，请重试一下！');
        }
        if( Auth::guard('company')->attempt(['username' => $request->username, 'password' => $request->password])
            or Auth::guard('company')->attempt(['mobile' => $request->username, 'password' => $request->password])){
            $user = Auth::guard('company')->user();

            if( CompanyUser::where('uid', $user->uid)->update(['wechatopenid' => session('openId'),
                'wechatunionid' => session('unionid')?session('unionid'):null]) ){
                Session::forget('openId');
                Session::forget('unionid');
                Session::forget('userImg');
                Session::forget('usname');
                //登录记录表
                $this->loginRecord($user);
                return redirect('company/welcome');
            }else{
                return back()->withErrors(['handleErr' => '绑定失败，请重试一下！']);
            }
        }else{
            return back()->withErrors(['handleErr' => '密码错误！']);
        }
    }

    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($userInfo){
        //登录记录表
        $record = array();
        $record['uid'] = $userInfo->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 2;
        $record['type'] = 3;
        //登录记录表
        CompanyLoginRecord::create($record);

        //更新用户表
        $currtime = date('Y-m-d H:i:s',time());
        $fifedate = date('Y-m-d H:i:s',strtotime($userInfo->surpris_visit_time . "+15 day"));
        if($fifedate < $currtime ){
            $userInfo->surpris_visit_time = date('Y-m-d H:i:s',time());
            //15天内插入突访记录表
            CompanyVisitRecord::create($record);
        }
        $userInfo->last_login_time = date('Y-m-d H:i:s',time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();

    }

    /**
     * 更新用户表记录
     * @param $userInfo
     */
    public function updateUser($userInfo){
        //更新用户表
        /*$currtime = date('Y-m-d H:i:s', time());
        $fifedate = date('Y-m-d H:i:s', strtotime($userInfo->surpris_visit_time . "+15 day"));
        if( $fifedate < $currtime ){
            $userInfo->surpris_visit_time = date('Y-m-d H:i:s', time());
        }
        $userInfo->last_login_time = date('Y-m-d H:i:s', time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();*/
    }

    /**
     * 自动登录，重命名用户名
     * @param $usname
     * @return string
     */
    
    protected function rename($usname){
        $CompanyUser = CompanyUser::select('username')->where('username',$usname)->first();
        if($CompanyUser){
            $reusname = $usname.'_'.str_random(8);
            return $this->rename($reusname);
        }else{
            return $usname;
        }
    }
}